<?php
require_once 'Datatype_integer.php';

class Datatype_dropdown extends Datatype_integer 
{
    private $_config;
    
    private static $_options = array();

    
    public function __construct(EDO_object_basic $owner, $config = array())
	{
		parent::__construct($owner, $config);	
	}
    
    
    public function getConfig()
    {
        if(!$this->_config)
        {
            $phrase = "SELECT * FROM datatype_dropdown WHERE typeid = {$this->getOwner()->getTypeid()} AND name = '{$this->getName()}'";
            $this->_config = $this->getOwner()->ldb->getRow($phrase);    
        }
        return $this->_config;
    }
    
    
    
    public function getOptions()
    {   
            
        
        $config = $this->getConfig();
        
        
        if(!isset(self::$_options[$config['source']]))
        {
            $sourceObj = $this->getOwner()->getHandler()->get($config['source']);
            
            
            $orderer = $config['order_by'];
            
            $options = $sourceObj->getFinder()->findAll(array(), $orderer);
            $opts = array();
            foreach($options as $obj)
            {
    	       $opts[$obj->edoid] = $this->resolveTags($obj, $config['display']);
    	    }
            
    	    self::$_options[$config['source']] = $opts;
        }
        
        

        return self::$_options[$config['source']]; 
           
    }
    
    
    public function resolveTags(EDO_object_basic $resolveObj, $resolve, $nullAsNull = false, $resolver = '_replacer')
    {
        $this->_resolveObj = $resolveObj;
        $this->_nullAsNull = $nullAsNull;
        
        $regexp = "/(\%([a-zA-Z_]*))/si";
        $resolved = preg_replace_callback($regexp, array($this, $resolver), $resolve);
        
        $this->_resolveObj = null;
               
        return $resolved;
    }

	    
    private function _replacer($matches)
    {
        $returner = $this->_resolveObj->getField($matches[2]);
        if(!$returner AND $this->_nullAsNull)
            $returner = 'null';
        
        return $returner;
    }

    
    
}